<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>知识库上传</title>
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 min-h-screen p-8">
<div class="max-w-2xl mx-auto bg-white rounded-xl shadow-md p-6">
  <h1 class="text-2xl font-bold text-gray-800 mb-6">知识库上传</h1>

  <!-- 错误提示 -->
  <div id="error" class="hidden mb-4 p-3 bg-red-100 text-red-700 rounded-lg"></div>

  <!-- 上传表单 -->
  <form id="uploadForm" class="space-y-4">
    <!-- 知识库名称 -->
    <div>
      <label class="block text-sm font-medium text-gray-700 mb-1">知识库名称</label>
      <input
              type="text"
              id="ragTag"
              class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              placeholder="请输入知识库名称"
              required>
    </div>

    <!-- 文件上传区域 -->
    <div>
      <label class="block text-sm font-medium text-gray-700 mb-1">选择文件</label>
      <div class="flex items-center justify-center w-full">
        <label class="flex flex-col w-full border-2 border-dashed rounded-lg hover:border-gray-400 transition-colors h-32">
          <div class="flex flex-col items-center justify-center pt-5 h-full">
            <svg class="w-8 h-8 text-gray-400 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"/>
            </svg>
            <span class="text-sm text-gray-500">点击选择文件或拖拽到此区域</span>
            <span class="text-xs text-gray-400">支持格式：md, txt, sql</span>
          </div>
          <input
                  type="file"
                  id="fileInput"
                  class="hidden"
                  multiple
                  accept=".md,.txt,.sql">
        </label>
      </div>

      <!-- 文件列表 -->
      <div id="fileList" class="mt-2 space-y-1"></div>
    </div>

    <!-- 上传按钮 -->
    <button
            type="submit"
            class="w-full bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700 transition-colors flex items-center justify-center">
      <svg id="spinner" class="hidden w-4 h-4 mr-2 animate-spin" viewBox="0 0 24 24">
        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none"/>
        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"/>
      </svg>
      开始上传
    </button>
  </form>
</div>

<script>
  const form = document.getElementById('uploadForm');
  const fileInput = document.getElementById('fileInput');
  const fileList = document.getElementById('fileList');
  const errorDiv = document.getElementById('error');
  const spinner = document.getElementById('spinner');

  // 显示文件列表
  fileInput.addEventListener('change', () => {
      fileList.innerHTML = '';
      Array.from(fileInput.files).forEach(file => {
          const div = document.createElement('div');
          div.className = 'text-sm text-gray-600 flex justify-between items-center';
          div.innerHTML = `
              <span>${file.name}</span>
              <span class="text-gray-400">${(file.size / 1024).toFixed(2)}KB</span>
          `;
          fileList.appendChild(div);
      });
  });

  // 提交表单
  form.addEventListener('submit', async (e) => {
      e.preventDefault();

      const ragTag = document.getElementById('ragTag').value.trim();
      const files = fileInput.files;

      // 验证输入
      if (!ragTag) {
          showError('请输入知识库名称');
          return;
      }
      if (files.length === 0) {
          showError('请选择至少一个文件');
          return;
      }

      // 验证文件类型
      const allowedTypes = ['text/markdown', 'text/plain', 'application/sql'];
      const invalidFiles = Array.from(files).filter(file =>
          !allowedTypes.includes(file.type)
      );
      if (invalidFiles.length > 0) {
          showError(`无效文件类型：${invalidFiles.map(f => f.name).join(', ')}`);
          return;
      }

      // 开始上传
      try {
          toggleLoading(true);
          const formData = new FormData();
          formData.append('ragTag', ragTag);
          Array.from(files).forEach(file => {
              formData.append('file', file);
          });

          const response = await fetch('http://localhost:8090/api/v1/rag/file/upload', {
              method: 'POST',
              body: formData
          });

          const result = await response.json();
          if (result.code === '0000') {
              alert('上传成功！');
              form.reset();
              fileList.innerHTML = '';
          } else {
              showError(result.info || '上传失败');
          }
      } catch (err) {
          showError('网络错误，请稍后重试');
      } finally {
          toggleLoading(false);
      }
  });

  function showError(message) {
      errorDiv.textContent = message;
      errorDiv.classList.remove('hidden');
      setTimeout(() => errorDiv.classList.add('hidden'), 3000);
  }

  function toggleLoading(isLoading) {
      spinner.classList.toggle('hidden', !isLoading);
      form.querySelector('button').disabled = isLoading;
  }
</script>
</body>
</html>
